package com.travel.server.manager.impl.dal;

import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.server.manager.dao.QuestionnaireInfoDao;
import com.travel.server.manager.model.QuestionnaireInfo;
import com.travel.server.manager.model.QuestionnaireInfoExample;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/16 18:09
 * @Desc:
 */
@Component
@Slf4j
public class QuestionnaireDal {

    @Autowired
    private QuestionnaireInfoDao questionnaireInfoDao;

    public QuestionnaireInfo selectById(Integer id){
        QuestionnaireInfo questionnaireInfo = questionnaireInfoDao.selectByPrimaryKey(id);
        if(questionnaireInfo == null){
            log.info("未查询到问卷信息，id {}", id);
            throw new WorkException(WorkCode.RECORD_NOT_EXIST);
        }
        return questionnaireInfo;
    }

    public Integer insertOrUpdate(QuestionnaireInfo questionnaireInfo){
        if(questionnaireInfo.getId() == null){
            questionnaireInfoDao.insertSelective(questionnaireInfo);
        }else{
            questionnaireInfoDao.updateByPrimaryKey(questionnaireInfo);
        }
        return questionnaireInfo.getId();
    }

    public PageDto<QuestionnaireInfo> select(QuestionnaireParam param){
        QuestionnaireInfoExample example = makeExample(param);
        int total = questionnaireInfoDao.countByExample(example);
        example.setOrderByClause("update_time desc");
        List<QuestionnaireInfo> list = questionnaireInfoDao.selectByExample(example);

        PageDto pageDto = new PageDto();
        pageDto.setList(list);
        pageDto.setTotal(total);
        return pageDto;
    }

    public List<QuestionnaireInfo> selectByExample(QuestionnaireParam param){
        if(param == null){
            param = new QuestionnaireParam();
        }
        QuestionnaireInfoExample example = makeExample(param);
        return questionnaireInfoDao.selectByExample(example);
    }

    private QuestionnaireInfoExample makeExample(QuestionnaireParam param){
        QuestionnaireInfoExample example = new QuestionnaireInfoExample();
        QuestionnaireInfoExample.Criteria criteria = example.or();
        if(param.getState() != null){
            criteria.andStateEqualTo(param.getState());
        }
        if(param.getLimit() != null && param.getOffset() != null){
            example.setOffset(param.getOffset());
            example.setLimit(param.getLimit());
        }
        return example;
    }

    @Data
    public static class QuestionnaireParam{
        private Integer offset;

        private Integer limit;

        private Integer state = 1;
    }
}
